package com.hsurosy.domain.activity.service.partake;

import com.hsurosy.domain.activity.model.aggregate.CreatePartakeOrderAggregate;
import com.hsurosy.domain.activity.model.entity.*;
import com.hsurosy.domain.activity.model.valobj.UserRaffleOrderStateVO;
import com.hsurosy.domain.activity.repository.IActivityRepository;
import com.hsurosy.types.enums.ResponseCode;
import com.hsurosy.types.exception.AppException;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-10 15:20
 * @Description
 * @Version: v1.0.0
 */
@Service
public class RaffleActivityPartakeService extends AbstractRaffleActivityPartake {

    private final SimpleDateFormat dateFormatMonth = new SimpleDateFormat("yyyy-MM"); // 格式化器：用于生成月时间格式
    private final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd"); // 格式化器：用于生成日时间格式

    public RaffleActivityPartakeService(IActivityRepository activityRepository) {
        super(activityRepository);
    }

    /**
     * 校验和筛选用户的账户额度信息，构建创建订单的聚合对象
     *
     * @param userId 用户ID
     * @param activityId 活动ID
     * @param currentDate 当前日期，用于校验月和日账户额度
     * @return 返回创建参与订单的聚合对象
     * @throws AppException 如果账户总额度、月额度或日额度不足，抛出异常
     */
    @Override
    protected CreatePartakeOrderAggregate doFilterAccount(String userId, Long activityId, Date currentDate) {
        // 查询用户的活动总账户信息
        ActivityAccountEntity activityAccountEntity = activityRepository.queryActivityAccountByUserId(userId, activityId);
        // 校验总额度是否足够（只判断总剩余额度）
        if (null == activityAccountEntity || activityAccountEntity.getTotalCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
        }

        String month = dateFormatMonth.format(currentDate); // 格式化为月字符串
        String day = dateFormatDay.format(currentDate); // 格式化为日字符串

        // 查询用户的月账户额度信息
        ActivityAccountMonthEntity activityAccountMonthEntity = activityRepository.queryActivityAccountMonthByUserId(userId, activityId, month);
        // 校验月额度是否足够断（只判断月剩余额度）
        if (null != activityAccountMonthEntity && activityAccountMonthEntity.getMonthCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
        }

        // 判断是否存在月账户并初始化为必要的默认值
        // 创建月账户额度：true = 存在月账户、false = 不存在月账户
        boolean isExistAccountMonth = null != activityAccountMonthEntity;
        if (null == activityAccountMonthEntity) {
            activityAccountMonthEntity = new ActivityAccountMonthEntity();
            activityAccountMonthEntity.setUserId(userId);
            activityAccountMonthEntity.setActivityId(activityId);
            activityAccountMonthEntity.setMonth(month);
            activityAccountMonthEntity.setMonthCount(activityAccountEntity.getMonthCount());
            activityAccountMonthEntity.setMonthCountSurplus(activityAccountEntity.getMonthCount());
        }

        // 查询用户的日账户额度信息
        ActivityAccountDayEntity activityAccountDayEntity = activityRepository.queryActivityAccountDayByUserId(userId, activityId, day);
        // 校验日额度是否足够（只判断月剩余额度）
        if (null != activityAccountDayEntity && activityAccountDayEntity.getDayCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo());
        }

        // 判断是否存在日账户并初始化为必要的默认值
        // 创建日账户额度：true = 存在日账户、false = 不存在日账户
        boolean isExistAccountDay = null != activityAccountDayEntity;
        if (null == activityAccountDayEntity) {
            activityAccountDayEntity = new ActivityAccountDayEntity();
            activityAccountDayEntity.setUserId(userId);
            activityAccountDayEntity.setActivityId(activityId);
            activityAccountDayEntity.setDay(day);
            activityAccountDayEntity.setDayCount(activityAccountEntity.getDayCount());
            activityAccountDayEntity.setDayCountSurplus(activityAccountEntity.getDayCount());
        }

        // 创建并返回聚合对象
        CreatePartakeOrderAggregate createPartakeOrderAggregate = new CreatePartakeOrderAggregate();
        createPartakeOrderAggregate.setUserId(userId);
        createPartakeOrderAggregate.setActivityId(activityId);
        createPartakeOrderAggregate.setActivityAccountEntity(activityAccountEntity);
        createPartakeOrderAggregate.setExistAccountMonth(isExistAccountMonth);
        createPartakeOrderAggregate.setActivityAccountMonthEntity(activityAccountMonthEntity);
        createPartakeOrderAggregate.setExistAccountDay(isExistAccountDay);
        createPartakeOrderAggregate.setActivityAccountDayEntity(activityAccountDayEntity);

        return createPartakeOrderAggregate;
    }

    /**
     * 构建用户抽奖订单
     *
     * @param userId 用户ID
     * @param activityId 活动ID
     * @param currentDate 当前日期
     * @return 返回用户抽奖订单实体
     */
    @Override
    protected UserRaffleOrderEntity buildUserRaffleOrder(String userId, Long activityId, Date currentDate) {
        // 查询活动基本信息
        ActivityEntity activityEntity = activityRepository.queryRaffleActivityByActivityId(activityId);
        // 构建用户抽奖订单实体
        UserRaffleOrderEntity userRaffleOrderEntity = UserRaffleOrderEntity.builder()
                .userId(userId)
                .activityId(activityId)
                .activityName(activityEntity.getActivityName())
                .strategyId(activityEntity.getStrategyId())
                .orderId(RandomStringUtils.randomNumeric(12)) // 生成订单ID
                .orderTime(currentDate) // 设置订单时间
                .orderState(UserRaffleOrderStateVO.create) // 初始状态为创建状态
                .endDateTime(activityEntity.getEndDateTime())
                .build();
        return userRaffleOrderEntity;
    }

}
